package com.pzhuweb.sgblog.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pzhuweb.sgblog.domain.entity.Article;
import com.pzhuweb.sgblog.service.ArticleService;
import com.pzhuweb.sgblog.domain.utils.RedisCache;
import com.pzhuweb.sgblog.domain.utils.SystemConstants;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Component
public class UpdateViewCountJob {

    @Resource
    private RedisCache redisCache;

    @Resource
    private ArticleService articleService;

    @Scheduled(cron = "0 0/2 * * * ?")  // 表示每两分钟执行一次
    public void updateViewCountJob() {
        // 从Redis中获取文章的浏览量数据
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(SystemConstants.VIEW_COUNT);

        if (!viewCountMap.isEmpty()) {
            // 获取数据库中现有的文章浏览量数据
            LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Article::getId, viewCountMap.keySet());
            List<Article> articlesToUpdate = articleService.list(queryWrapper);

            // 更新文章的浏览量数据
            for (Article article : articlesToUpdate) {
                String articleId = String.valueOf(article.getId());
                if (viewCountMap.containsKey(articleId)) {
                    Integer viewCount = viewCountMap.get(articleId);
                    article.setViewCount(viewCount.longValue());
                }
            }
            // 使用updateBatchById方法进行批量更新
            articleService.updateBatchById(articlesToUpdate);
        }
    }
}
